package com.pkk.cloud.support.oauth2.princiapl.handle;

import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.boot.autoconfigure.security.oauth2.resource.FixedPrincipalExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;

/**
 * @author peikunkun<br>
 * @version V1.0<br>
 * @Title: 获取自定义token的用户信息<br>
 * @Description: <><br>
 * @date 2020/3/19 0019 下午 4:32<br>
 * @URL:[]
 */

public class UserPrincipalExtractor implements PrincipalExtractor {

  private FixedPrincipalExtractor fixedPrincipalExtractor = new FixedPrincipalExtractor();

  /**
   * @Description: 提取用户主题信息
   * @Param: map
   * @return: java.lang.Object
   * @Author: peikunkun
   * @Date: 2020/3/21 0021 下午 4:33
   */
  @Override
  public Object extractPrincipal(Map<String, Object> map) {
    Map<String, Object> authentication = (Map<String, Object>) map.get("userAuthentication");
    if (authentication != null) {
      LinkedHashMap<String, Object> principal = (LinkedHashMap<String, Object>) authentication.get("principal");
      try {
        Object userInfo = principal.get("userInfo");
        return userInfo;
      } catch (Exception e) {
        throw new InvalidTokenException("错误的token信息,无法获取用户信息");
      }
    } else {
      Object principal = this.fixedPrincipalExtractor.extractPrincipal(map);
      return (principal == null ? "unknown" : principal);
    }
  }
}
